package com.colter.project.sample.thread.part03.test1;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Exchanger;

public class Test72 {
	public static void main(String[] args) {
		Exchanger<List<Object>> exchanger = new Exchanger<>();
		new Thread(new Producer1(exchanger)).start();
		new Thread(new Consumer1(exchanger)).start();;
	}
}

class Producer1 implements Runnable {
	List<Object> list = new ArrayList<>();
	private Exchanger<List<Object>> exchanger;

	public Producer1(Exchanger<List<Object>> exchanger) {
		super();
		this.exchanger = exchanger;
	}

	@Override
	public void run() {
		Random random = new Random();
		list.add(random.nextInt(100));
		list.add(random.nextInt(100));
		list.add(random.nextInt(100));
		list.add(random.nextInt(100));
		list.add(random.nextInt(100));
		System.out.println("Producer:"+list + " before change");
		try {
			list = exchanger.exchange(list);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("Producer:"+list + " end change");
	}
}


class Consumer1 implements Runnable {
	List<Object> list = new ArrayList<>();
	private Exchanger<List<Object>> exchanger;

	public Consumer1(Exchanger<List<Object>> exchanger) {
		super();
		this.exchanger = exchanger;
	}

	@Override
	public void run() {
		System.out.println("Consumer:"+list + " before change");
		try {
			list = exchanger.exchange(list);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("Consumer:"+list + " end change");
	}
}